//index.js
//获取应用实例
import { getPublic, actionsIndex, getuserInfo } from '../../api/api.js';
import { tips } from '../../utils/show.js';
import { formatDateChain } from '../../utils/util.js';
import authLogin from '../../utils/authLogin'
const app = getApp()
Page({
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '福康汇', // 导航栏 中间的标题
    },
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20 ,
    // 轮播图数据
    swiperImgUrl: [],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    // 商品数据
    storeList: [],
    // 判断是否登陆
    avatar: '../../image/head.png',
    text: '未登录',
    imgUrl: app.globalData.imgUrl
  },

  activity: function () {
    wx.navigateTo({
      url: '/pages/index/activityList/activityList' //跳转的页面地址 可以跟多个参数
    })
  },

  fun: function () {
    wx.switchTab({
      url: '/pages/fun/fun' //跳转的页面地址 可以跟多个参数
    })
  },

  goMe: function() {
    wx.switchTab({
      url: '/pages/me/me'
    })
  },

  // 跳转到签到页面
  sign: function () {
    if (!app.globalData.hasLogin || !app.globalData.hasMobile) {
      wx.navigateTo({  url: '/pages/me/login/login' })
    }  else {
      wx.navigateTo({ url: '/pages/me/sign/sign' });
    }
  },

  onLoad: function () {
    this.getSwiperImg();
    this.getactionsIndex();
    this.getUserInfo();
  },

  getSwiperImg () {
    var that = this;
    getPublic().then(res =>{
      let newswi = new Array; 
      if (res.code == 1) { 
        const swiperImg = res.data.slide;
        const storeImg = res.data.store.slice(0,2);
        // 赋值给轮播图
        that.setData({
          swiperImgUrl: swiperImg,
          storeList: storeImg
        });
      } else {
        // 异常处理
      }
    })
  },

  getactionsIndex(){
    actionsIndex().then(res =>{
      if (res.code === 0) {
        let nowtime = Math.floor((new Date()).getTime()/1000);
        res.data.forEach(item => {
          // 拿到时间对比
          let begin_time = parseInt(item.begin_time);
          let end_time = parseInt(item.end_time);
          if (nowtime < begin_time) {
            item.status = 1;
            item.statusText = '未开始';
          } else if (begin_time < nowtime && nowtime < end_time) {
            item.status = 2;
            item.statusText = '报名中';
          } else {
            item.status = 3;
            item.statusText = '已截止';
          }
          item.begin_time = formatDateChain(item.begin_time);
          item.end_time = formatDateChain(item.end_time);
        });
        // console.log(res.data)
        let act = res.data;
        this.setData({
          activitys:act
        });
      } else {
        tips("数据出错");
      }
    })
  },

  auth () {
    if (!app.globalData.hasLogin || !app.globalData.hasMobile) {
      wx.navigateTo({  url: '/pages/me/login/login' })
    }
  },

  //跳转到活动详情
  goActivity(e){
    if (!app.globalData.hasLogin || !app.globalData.hasMobile) {
      wx.navigateTo({  url: '/pages/me/login/login' })
    } else {
      let id = e.currentTarget.dataset.id;
      let status = e.currentTarget.dataset.status;
      if (status == 3) {
        app.showToast('活动已截止');
        return;
      } else if (status == 1) {
        app.showToast('活动未开始');
        return;
      } 
      wx.navigateTo({
        url: '/pages/index/activityList/activityList?id=' + id,
      })
    }
  },

  getUserInfo () {
    app.showLoading();
    app.setting()
      .then(res => {
        // console.log(res);
        if (res.authSetting['scope.userInfo'] === true) {
          return app.getWxInfo();
        } else {
          // TODO 用户未授权
          app.hideLoading();
          return;
        }
      })
      .then(res => {
        res.avatar = res.avatarUrl;
        app.globalData.userInfo = res;
        app.globalData.hasLogin = true;
        this.setData({
          avatar: res.avatar,
          text: '您好！欢迎进入福康汇'
        });
        return app.login();
      })
      .then(res => {
        // console.log(res);
        return app.checkUser({ openid: res.openid });
      }).then(res => {
        if (res.code == 0 && res.data.mobile) {
          // res.data.avatar = app.globalData.imgUrl + res.data.avatar;
          app.globalData.hasMobile = true;
          app.globalData.userId = res.data.id;
          app.globalData.userInfo = res.data;
          // console.log(res.data)
        }
        resolve();
        this.hideLoading();
      }).catch(err => {
        app.hideLoading();
      });
  },
  
  goGoodsDetail (e) {
    const id = e.currentTarget.dataset.type;
    wx.navigateTo({ url: '/pages/fun/details/details?id=' +id });
  },
  guarantee: function () {
    wx.navigateTo({ url: '/pages/have/repair/repair' })
  },
  selectService: function () {
    wx.navigateTo({ url: '/pages/have/service/service' })
  },
  goActionList: function () {
    if (!app.globalData.hasLogin || !app.globalData.hasMobile) {
      wx.navigateTo({  url: '/pages/me/login/login' })
    }  else {
      wx.navigateTo({ url: '/pages/index/details/index' })
    }
    
  },

  onShow () {
    const user = app.globalData.userInfo || {};
    const arr = Object.keys(user);
    // console.log(user);
    if (arr.length !== 0) {
      this.setData({
        avatar:  user.avatar,
        text: '您好！欢迎进入福康汇'
      })
    }
    // console.log(app.globalData.openid);
  },

  checkUser () {
    const { openid, userId } = app.globalData;
    if ( userId && openid ) {
      getuserInfo({openid}).then(res => {
        app.globalData.userInfo = res.data;
        app.globalData.userId = res.data.id;
      })
      return
    } else if (res.openid) {
      // 判断用户是否授权
      wx.getSetting({
        success (res) {
          if (res.authSetting['scope.userInfo'] === true) {
            wx.getUserInfo({
              success ({rawData}) {
                const data = JSON.parse(rawData);
                resolve(data);
              }
            })
          } else {
            // TODO 用户未授权
            return;
          }
        }
      })
    } else {
    }
  }
})
